package com.ocean.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * https://leetcode.cn/problems/n-ary-tree-preorder-traversal/
 * <p>
 * n叉树前序遍历
 */
public class NAryTreePreorderTraversal {

    public static void main(String[] args) {
        NAryTreePreorderTraversal traversal = new NAryTreePreorderTraversal();
        Node root = Node.getRoot();
        List<Integer> res = traversal.preorder2(root);
        System.out.println(res);
    }

    /**
     * [1,2,3,6,7,11,14,4,8,12,5,9,13,10]
     *
     * @param root
     * @return
     */
    public List<Integer> preorder(Node root) {
        List<Integer> res = new ArrayList<>();
        preorder(root, res);
        return res;
    }

    public void preorder(Node root, List<Integer> res) {
        if (root == null) {
            return;
        }
        res.add(root.val);
        if (root.children == null || root.children.isEmpty()) {
            return;
        }
        for (Node child : root.children) {
            preorder(child, res);
        }
    }

    public List<Integer> preorder2(Node root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node cur = stack.pop();
            res.add(cur.val);
            if (cur.children == null) {
                continue;
            }
            for (int i = cur.children.size() - 1; i >= 0; i--) {
                stack.push(cur.children.get(i));
            }
        }
        return res;
    }
}
